package com.leapp.sk.ui.activity.login

import android.content.Intent
import android.os.Bundle
import android.os.CountDownTimer
import android.text.TextUtils
import android.view.View
import cc.vv.lkbasecomponent.http.LKHttp
import cc.vv.lkbasecomponent.http.lib.setting.Settings
import cc.vv.lkbasecomponent.util.LKSPUtil
import cc.vv.lklibrary.http.base.okhttpfactory.plugins.httpplugin.MediaTypeWrap
import cc.vv.lklibrary.log.LogOperate
import com.example.baselibrary.db.dao.GroupDao
import com.example.baselibrary.db.table.GroupTable
import com.example.baselibrary.util.LKToastUtil
import com.example.mvp.activity.BaseActivityMVP
import com.example.mvp.binder.BaseDataBinder
import com.example.mvp.view.CabcelSureDialog
import com.leapp.sk.R
import com.leapp.sk.binder.login.LoginBinder
import com.leapp.sk.util.wxentry.WXLoginUtil
import com.leapp.sk.viewdelegate.login.LoginDelegate
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.example.baselibrary.util.SKPermissionUtils
import com.example.jpush.LKJPushManager
import com.example.util.*
import com.example.im.IMInit
import com.leapp.sk.app.CLASS_LIST
import com.leapp.sk.app.GET_CODE
import com.leapp.sk.app.LOGIN
import com.leapp.sk.bean.ClassListEntity
import com.leapp.sk.bean.UserInfoEntity
import com.leapp.sk.bean.request.classs.ClassListRequestEntity
import com.leapp.sk.bean.request.login.LoginRequestEntity
import com.leapp.sk.bean.request.login.SendCodeRequestEntity
import com.leapp.sk.bean.response.classs.ClassListResponseEntity
import com.leapp.sk.bean.response.login.LoginResponseEntity
import com.leapp.sk.bean.response.login.SendCodeResponseEntity
import com.leapp.sk.sever.login.UserInfoSever
import com.leapp.sk.ui.activity.AppMainTableActivity
import com.leapp.sk.ui.activity.join.SearchClassActivity
import com.leapp.sk.ui.activity.join.ToExamineActivity
import com.example.util.finallist.KEY_ACCOUNT
import com.example.util.finallist.KEY_CLASS_ID
import com.example.util.finallist.KEY_CLASS_TYPE
import com.example.util.finallist.SKCODE_200
import java.util.HashSet


/**
 * 登录页面
 * @author  chaohaipeng  on 2018/7/10.
 */
class LoginActivity : BaseActivityMVP<LoginDelegate>() {
    /**
     * 微信登录相关
     */
    var api: IWXAPI? = null
    /**
     * 计时器
     */
    private var timeCount: TimeCount? = null
    /**
     * dialog
     */
    private var cabcelSureDialog: CabcelSureDialog? = null
    val set = HashSet<String>()
    /**
     * 验证码
     */
    private var code: String?= ""
    override fun initView(p0: Bundle?) {
        cabcelSureDialog?.setDialogContent(resources.getString(R.string.string_login_dialog_content))
        cabcelSureDialog?.setDialogConfirm(resources.getString(R.string.string_login_dialog_ok))
        viewDelegate?.setClearDatavisible()
    }
    override fun initDate() {
        SKPermissionUtils.getInstance().requestSD(this)
        SKPermissionUtils.getInstance().requestCamera(this)
        api = WXLoginUtil.initWXEntryLogin(this)
        //构造CountDownTimer对象
        timeCount = TimeCount(60000, 1000)
        cabcelSureDialog = CabcelSureDialog(this, com.example.baselibrary.R.style.dialog_style)

        val account = LKSPUtil.getInstance().getString(KEY_ACCOUNT)
        if (!TextUtils.isEmpty(account)){
            viewDelegate.setPhone(account)
        }
    }

    override fun bindEvenListener() {
        viewDelegate.setOnClickListener(View.OnClickListener {
            if (!TextUtils.isEmpty(viewDelegate?.verificationCodeCheck())) {
                timeCount?.start()
            httpCode(viewDelegate?.verificationCodeCheck())
            }
        }, R.id.tv_al_get_code)
        viewDelegate.setOnClickListener(View.OnClickListener {
            cabcelSureDialog?.show()
        }, R.id.iv_al_wx_login)

        viewDelegate.setOnClickListener(View.OnClickListener {
            if (!TextUtils.isEmpty(viewDelegate.verificationCodeCheck()) && !TextUtils.isEmpty(viewDelegate.loginCheck())) {
               httpLogin(viewDelegate.verificationCodeCheck(), code)
            }

        }, R.id.tv_al_login)

        viewDelegate.setOnClickListener(View.OnClickListener {
            val intent: Intent = Intent(this, UserAgreementActivity::class.java)
            startActivity(intent)
        }, R.id.tv_al_user_agressment)
        cabcelSureDialog?.setEventInterface(object : CabcelSureDialog.DialogEventInterface {
            override fun leftOnClick() {
                cabcelSureDialog?.cancel()
            }

            override fun rightOnClick() {
                cabcelSureDialog?.cancel()
                WXLoginUtil.sendRequest(api)
            }
        })


        viewDelegate.setOnClickListener(View.OnClickListener {
            viewDelegate.clearContent()
        }, R.id.iv_al_clear_content)

    }


    /**
     * 获取验证码
     */
    private fun httpCode(phone: String?) {
        if(phone==null){
          return
        }
        val sendCodeRequest = SendCodeRequestEntity()
        sendCodeRequest.phone = phone
        LKHttp.post(GET_CODE, sendCodeRequest, SendCodeResponseEntity::class.java, object : BaseCallBack<SendCodeResponseEntity>(this) {
            override fun onSuccess(url: String?, resultText: String?, obj: SendCodeResponseEntity?) {
                super.onSuccess(url, resultText, obj)
                if (obj?.code == SKCODE_200) {
                    val data = obj.data
                    code=data
                    viewDelegate.setverificationCode(data)
                }else{
                    LKToastUtil.showToastShort(obj?.message)
                }
            }
            override fun onFailure(url: String?, isLoading: Boolean, exceptionStr: String?) {
                super.onFailure(url, isLoading, exceptionStr)
                LKToastUtil.showToastShort(resources.getString(R.string.app_net_erro))
            }
        }
                , true, Settings(MediaTypeWrap.MEDIA_TYPE_FORM))
    }
    /**
     * 登录
     */
    private fun httpLogin(phone: String, password: String?) {
        if (password==null){
            return
        }
        val loginRequestEntity = LoginRequestEntity()
        loginRequestEntity.phone = phone
        loginRequestEntity.password = password
        loginRequestEntity.type=2
        LKHttp.post(LOGIN, loginRequestEntity, LoginResponseEntity::class.java, object : BaseCallBack<LoginResponseEntity>(this) {
            override fun onSuccess(url: String?, resultText: String?, obj: LoginResponseEntity?) {
                super.onSuccess(url, resultText, obj)
                if (obj?.code == SKCODE_200) {
                    LKSPUtil.getInstance().put(KEY_ACCOUNT,phone)

                    UserInfoSever.getInstance().saveData(obj)
                    val userInfoEntity: UserInfoEntity = ObjectProcessingUtil.objMandatoryConversionClass(obj?.data, UserInfoEntity::class.java)
                    IMInit.getInstance().login(userInfoEntity?.id!!)
                    httpGetClass(userInfoEntity?.id!!)
                    setTag(userInfoEntity.jpushTags)
                    val name=userInfoEntity?.name
                    ISTECHER = userInfoEntity?.type==1
                    if (userInfoEntity.status==0){
                        if (TextUtils.isEmpty(name)){
                            ISHAVECLASS=false
                            val intent: Intent = Intent(this@LoginActivity, PerfectUserInfoActivity::class.java)
                            startActivity(intent)
                        }else{
                            ISHAVECLASS=false
                            val intent: Intent = Intent(this@LoginActivity, SearchClassActivity::class.java)
                            startActivity(intent)
                        }
                    }else if (userInfoEntity.status==1){
                        ISHAVECLASS=true
                        val intent: Intent = Intent(this@LoginActivity, AppMainTableActivity::class.java)
                        startActivity(intent)
                        this@LoginActivity.finish()
                    }else{
                        ISHAVECLASS=false
                        val intent: Intent = Intent(this@LoginActivity, ToExamineActivity::class.java)
                        startActivity(intent)
                    }
                }else{
                    LogOperate.e("消息======="+obj?.message)
                    LKToastUtil.showToastShort(obj?.message)
                }
            }
            override fun onFailure(url: String?, isLoading: Boolean, exceptionStr: String?) {
                super.onFailure(url, isLoading, exceptionStr)
               LKToastUtil.showToastShort(resources.getString(R.string.app_net_erro))
            }
        }
                , true, Settings(MediaTypeWrap.MEDIA_TYPE_FORM))

    }

    /**
     * 极光推送设置Tag
     */
   private fun setTag(jpushTags:String?){
       set.clear()
        LKJPushManager.getInstance()
       if (!TextUtils.isEmpty(jpushTags)){
           val split = jpushTags?.split(",")
           if(split!=null&&split.size>0){
               for (i in split.indices){
                   set.add(split.get(i))
               }
               LKJPushManager.getInstance().setTags(this@LoginActivity,set)
           }
       }







   }
    /**
     * 获取班级
     */
    private fun httpGetClass(userId:String) {
        val type= LKSPUtil.getInstance().getInt(KEY_CLASS_TYPE, 0)
        val classListRequestEntity = ClassListRequestEntity()
        classListRequestEntity.userId=userId
        classListRequestEntity.type=type
        LKHttp.post(CLASS_LIST, classListRequestEntity, ClassListResponseEntity::class.java, object : BaseCallBack<ClassListResponseEntity>(this) {
            override fun onSuccess(url: String?, resultText: String?, obj: ClassListResponseEntity?) {
                super.onSuccess(url, resultText, obj)
                if (obj?.code == SKCODE_200) {
                    val objMandatoryConversionClass = ObjectProcessingUtil.objMandatoryConversionClass(obj?.data, mutableListOf<ClassListEntity>())
                    if (objMandatoryConversionClass!=null&&objMandatoryConversionClass.size>0){
                        val get = objMandatoryConversionClass.get(0)
                        LKSPUtil.getInstance().put(KEY_CLASS_ID,get?.id!!)
                        GroupDao.getInstance().updateCount(get?.groupId, get.total)
                        val groupTable = GroupTable()
                        groupTable.groupId = get?.groupId
                        groupTable.groupNick = get?.className
//                    groupTable.groupAvatar = data?.avatar
                        GroupDao.getInstance().updateGroup(groupTable)
                    }

                }else{
                    LKToastUtil.showToastShort(obj?.message)
                }
            }
            override fun onFailure(url: String?, isLoading: Boolean, exceptionStr: String?) {
                super.onFailure(url, isLoading, exceptionStr)
                LKToastUtil.showToastShort(resources.getString(R.string.app_net_erro))
            }
        }
                , true, Settings(MediaTypeWrap.MEDIA_TYPE_FORM))

    }






    override fun getDelegateClass(): Class<LoginDelegate> {
        return LoginDelegate::class.java
    }

    override fun getDataBinder(): BaseDataBinder<*, *> {
        return LoginBinder()
    }

    /**
     * 验证码倒计时
     */
    internal inner class TimeCount(millisInFuture: Long, countDownInterval: Long)//参数依次为总时长,和计时的时间间隔
        : CountDownTimer(millisInFuture, countDownInterval) {
        override fun onFinish() {
            //计时完毕时触发
            viewDelegate?.verificationCode(0)
        }

        override fun onTick(millisUntilFinished: Long) {
            // 计时过程显示
            viewDelegate?.verificationCode(millisUntilFinished)
        }
    }

}